package cn.cas.mango.util.RequestUtil;

import cn.cas.mango.dto.HotSpotNews;
import cn.cas.mango.service.ConfigService;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.FieldValue;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@Slf4j
public class GetIdsRequest {
  @Autowired
  private  ConfigService configService;

  @Autowired
  private ElasticsearchClient client;

  public SearchRequest getIds(List<String> ids) {
    SearchRequest searchRequest = SearchRequest.of(
        x -> x.index(configService.getIndex())
            .query(q -> q.terms(
                t -> t.field("nm").terms(v -> v.value(ids.stream().map(FieldValue::of).collect(Collectors.toList())))))
            .source(s -> s.filter(f -> f.excludes("vector"))));
    log.info(searchRequest.toString());
    return searchRequest;
  }

  public  List<HotSpotNews> batchGetIds(List<String> ids) {
    int batchSize = 10;
    List<HotSpotNews> ret = new ArrayList<>();
    int times = (int)Math.ceil(ids.size() * 1.0 / batchSize);
    for (int i = 0; i < times;i++) {
      int from_ = i * batchSize;
      int to_ = from_ + batchSize;
      to_ = Math.min(to_, ids.size());
      SearchRequest searchRequest = getIds(ids.subList(from_, to_));
      SearchResponse<HotSpotNews> response;
      try {
        response = client.search(searchRequest, HotSpotNews.class);
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
      List<HotSpotNews> res = response.hits().hits().stream().map(x -> x.source()).collect(Collectors.toList());
      ret.addAll(res);
    }
    return ret;

  }
}
